<?php

namespace App\Repositories;


use App\Enums\UserEnum;
use App\Enums\FinancialEnum;
use App\Exceptions\BasicException;
use App\Services\Tools\CommonService;
use Illuminate\Support\Facades\DB;
use App\Enums\ErmEnum;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use App\Enums\RedisKeyEnum;

//引入hash

class ErmPublicListRepository
{

    /*大众名单列表*/
    public function getPublicList($param, $page, $perPage, $type)
    {
        $ermPublicListModel = app("model_erm_public_list");
        $userDataModel = app('model_user_data');
        if (isset($param['user_code'])) {
            $whereArr['t2.user_code'] = $param['user_code'];
        }
        if (isset($param['nickname'])) {
            $whereArr[] = ['t2.nickname', 'like', '%' . $param['nickname'] . '%'];
        }
        if (isset($param['user_type'])) {
            $whereArr['t1.user_type'] = $param['user_type'];
        }
        if (isset($param['min_recharge_money'])) {
            $whereArr[] = ['t1.recharge_money', '>=', $param['min_recharge_money']];
        }
        if (isset($param['max_recharge_money'])) {
            $whereArr[] = ['t1.recharge_money', '<=', $param['max_recharge_money']];
        }
        if (isset($param['start_register_time'])) {
            $param['start_register_time'] = strtotime($param['start_register_time']);
            $whereArr[] = ['t1.register_time', '>=', $param['start_register_time']];
        }
        if (isset($param['end_register_time'])) {
            $param['end_register_time'] = strtotime($param['end_register_time']);
            $whereArr[] = ['t1.register_time', '<=', $param['end_register_time']];
        }
        if (isset($param['start_recharge_time'])) {
            $param['start_recharge_time'] = strtotime($param['start_recharge_time']);
            $whereArr[] = ['t1.last_recharge_time', '>=', $param['start_recharge_time']];
        }
        if (isset($param['end_recharge_time'])) {
            $param['end_recharge_time'] = strtotime($param['end_recharge_time']);
            $whereArr[] = ['t1.last_recharge_time', '<=', $param['end_recharge_time']];
        }
        if (isset($param['start_add_time'])) {
            $param['start_add_time'] = strtotime($param['start_add_time']);
            $whereArr[] = ['t1.update_time', '>=', $param['start_add_time']];
        }
        if (isset($param['end_add_time'])) {
            $param['end_add_time'] = strtotime($param['end_add_time']);
            $whereArr[] = ['t1.update_time', '<=', $param['end_add_time']];
        }
        $whereArr['t1.type'] = $type;
        $list = $ermPublicListModel
            ->from($ermPublicListModel->getTable() . ' as t1')
            ->selectRaw('t1.id,t2.nickname,t2.user_code,t1.user_type,t1.register_time,t1.recharge_num,t1.recharge_money,t1.last_recharge_time,t1.gray_num,t1.black_num,t1.white_num,t1.update_time,t1.create_time,t1.user_id')
            ->join($userDataModel->getTable() . ' as t2', 't1.user_id', '=', 't2.user_id')
            ->with('record:user_id,remark,operator_id')
            ->where($whereArr)
            ->orderBy("t1.last_recharge_time", "desc")
            ->paginate($perPage, ['*'], '', $page);

        foreach ($list as $item) {
            $item->user_type = ErmEnum::USER_TYPE[$item->user_type];
            $item->register_date = ceil((time() - $item->register_time) / 86400);
            $item->register_time = date('Y-m-d H:i:s', $item->register_time);
            $item->last_recharge_time = $item->last_recharge_time ? date('Y-m-d H:i:s', $item->last_recharge_time) : '-';
            $item->join_time = date('Y-m-d H:i:s', $item->update_time ? $item->update_time : $item->create_time);
            $item->bold = 0;
            if ($item->record && $item->record->remark == '超过风控次数') {
                $item->bold = 1;
            }
            unset($item->create_time, $item->update_time, $item->record);
        }

        return $list;
    }

    /*白/灰/黑名单列表*/
    public function getList($param, $page, $perPage, $type)
    {
        $ermPublicListModel = app("model_erm_public_list");
        $userDataModel = app('model_user_data');
        $ermAuthenticationRecordModel = app('model_erm_authentication_record');
        if (isset($param['user_code'])) {
            $whereArr['t2.user_code'] = $param['user_code'];
        }
        if (isset($param['nickname'])) {
            $whereArr[] = ['t2.nickname', 'like', '%' . $param['nickname'] . '%'];
        }
        if (isset($param['user_type'])) {
            $whereArr['t1.user_type'] = $param['user_type'];
        }
        if (isset($param['min_recharge_money'])) {
            $whereArr[] = ['t1.recharge_money', '>=', $param['min_recharge_money']];
        }
        if (isset($param['max_recharge_money'])) {
            $whereArr[] = ['t1.recharge_money', '<=', $param['max_recharge_money']];
        }
        if (isset($param['start_register_time'])) {
            $param['start_register_time'] = strtotime($param['start_register_time']);
            $whereArr[] = ['t1.register_time', '>=', $param['start_register_time']];
        }
        if (isset($param['end_register_time'])) {
            $param['end_register_time'] = strtotime($param['end_register_time']);
            $whereArr[] = ['t1.register_time', '<=', $param['end_register_time']];
        }
        if (isset($param['start_recharge_time'])) {
            $param['start_recharge_time'] = strtotime($param['start_recharge_time']);
            $whereArr[] = ['t1.last_recharge_time', '>=', $param['start_recharge_time']];
        }
        if (isset($param['end_recharge_time'])) {
            $param['end_recharge_time'] = strtotime($param['end_recharge_time']);
            $whereArr[] = ['t1.last_recharge_time', '<=', $param['end_recharge_time']];
        }
        if (isset($param['operator_id'])) {
            $whereArr['t1.operator_id'] = $param['operator_id'];
        }
        if (isset($param['start_add_time'])) {
            $param['start_add_time'] = strtotime($param['start_add_time']);
            $whereArr[] = ['t1.create_time', '>=', $param['start_add_time']];
        }
        if (isset($param['end_add_time'])) {
            $param['end_add_time'] = strtotime($param['end_add_time']);
            $whereArr[] = ['t1.create_time', '<=', $param['end_add_time']];
        }
        $whereArr['t1.type'] = $type;
        $fields = 't1.id,t2.nickname,t2.user_code,t1.user_type,t1.register_time,t1.recharge_num,t1.recharge_money,t1.last_recharge_time,t1.gray_num,t1.black_num,t1.update_time,t1.operator_id,t1.user_id,t1.white_num';
        $list = $ermPublicListModel
            ->from($ermPublicListModel->getTable() . ' as t1')
            // ->selectRaw('t1.id,t2.nickname,t2.user_code,t1.user_type,t1.register_time,t1.recharge_num,t1.recharge_money,t1.last_recharge_time,t1.gray_num,t1.black_num,t1.update_time,t1.operator_id,t1.user_id,t1.white_num')
            ->join($userDataModel->getTable() . ' as t2', 't1.user_id', '=', 't2.user_id');
        if (isset($param['auth_type'])) {
            $auth_type = $param['auth_type'];
            $list = $list->join($ermAuthenticationRecordModel->getTable() . ' as t3', function ($join) use ($auth_type) {
                $join->on('t1.user_id', '=', 't3.user_id')->where(['t3.type' => $auth_type, 't3.is_effect' => 0, 't3.detail_type' => ErmEnum::AUTO_REMOVE_GRAY_LIST]);
            });
        }
        if($type==ErmEnum::GRAY_TYPE) {
            $list->with("erm_gray_list:user_id,create_time,remark,prove");
            if (!empty($param['reason'])) {
                // 关联最后一条操作记录
                $list = $list->join(DB::raw('(SELECT user_id,remark,operator_id as op_id FROM ln_erm_list_record WHERE id IN(SELECT MAX(id) FROM ln_erm_list_record GROUP BY user_id)) t6'),
                    't1.user_id',
                    't6.user_id'
                );
                if($param['reason'] == '手动加灰'){
                    $list->where('t6.op_id','>',0);
                }else{
                    $list->where('t6.op_id',0);
                    $list->where('t6.remark','like',"%".$param['reason']);
                }
                $list->groupBy('t1.user_id');
                $fields .= ',t6.remark';
            }
        }
        if($type==ErmEnum::WHITE_TYPE) {
            $list->with("erm_white_list:user_id,create_time,expire_time,limit_num,remark");
        }
        if($type==ErmEnum::BLACK_TYPE) {
            $list->with("erm_black_list:user_id,create_time,remark,prove");
            if (!empty($param['reason'])) {
                $list = $list->join(
                    DB::raw('(SELECT user_id,remark,operator_id as op_id FROM ln_erm_list_record WHERE id IN(SELECT MAX(id) FROM ln_erm_list_record GROUP BY user_id)) t6'),
                    't1.user_id',
                    't6.user_id'
                );
                if ($param['reason'] == '手动加黑') {
                    $list->where('t6.op_id', '>', 0);
                } else {
                    $list->where('t6.op_id', 0);
                    $list->where('t6.remark', 'like', "%".$param['reason']);
                }
                $list->groupBy('t1.user_id');
                $fields .= ',t6.remark';
            }
        }

        $list->selectRaw($fields);

        $list->with("record:user_id,operator_id,id");

        $list = $list->with("admin:admin_id,admin_name")
            ->with([
                'erm_authentication_record' => function ($query) {
                    $query->select('user_id', 'type')->where(['status' => 1, 'is_effect' => 0, 'detail_type' => ErmEnum::AUTO_REMOVE_GRAY_LIST]);
                },
            ])
            ->where($whereArr)
            ->orderBy("t1.last_recharge_time", "desc")
            ->orderBy('t1.update_time', 'desc')
            ->paginate($perPage, ['*'], '', $page);

        $authentication_type = [1 => '充值', 2 => '消费', 3 => '提现', 4 => '兑换'];
        foreach ($list as $item) {
            $item->user_type = ErmEnum::USER_TYPE[$item->user_type];
            $item->register_date = ceil((time() - $item->register_time) / 86400);
            $item->register_time = date('Y-m-d H:i:s', $item->register_time);
            $item->last_recharge_time = $item->last_recharge_time ? date('Y-m-d H:i:s', $item->last_recharge_time) : '-';
            if($type==ErmEnum::GRAY_TYPE) {
                $item->join_time = date('Y-m-d H:i:s', $item->erm_gray_list->create_time);
                // $remark = $item->erm_gray_list->remark;
                // if ($remark) {
                //     $remark = strpos($remark, ':') !== false ? explode(':', $remark) : explode('：', $remark);
                //     $remark = count($remark) > 1 ? $remark[1] : $remark[0];
                // }
                // $item->remark = $remark;
                if ($item->record && $item->record->operator_id > 0) {
                    $item->reason = '手动加灰';
                    $item->remark = $item->erm_gray_list->remark;
                }else{
                    $item->reason = $item->erm_gray_list->remark;
                    $item->remark = '';
                }
                $item->prove = $item->erm_gray_list->prove;
                unset($item->erm_gray_list);
            }
            if($type==ErmEnum::WHITE_TYPE) {
                $item->join_time = date('Y-m-d H:i:s', $item->erm_white_list->create_time);
                if($item->erm_white_list->expire_time) {
                    $item->expire_time = date('Y-m-d H:i:s', $item->erm_white_list->expire_time);
                    $item->expire_day = ceil(($item->erm_white_list->expire_time - $item->erm_white_list->create_time) / 86400);
                }else{
                    $item->expire_day = 0;
                    $item->expire_time = '';
                }
                $item->limit_num = $item->erm_white_list->limit_num;
                // $remark = $item->erm_white_list->remark;
                // if ($remark) {
                //     $remark = strpos($remark, ':') !== false ? explode(':', $remark) : explode('：', $remark);
                //     $remark = count($remark) > 1 ? $remark[1] : $remark[0];
                // }
                // $item->remark = $remark;
                $item->remark = $item->erm_white_list->remark;
                unset($item->erm_white_list);
            }
            if($type==ErmEnum::BLACK_TYPE) {
                $item->join_time = date('Y-m-d H:i:s', $item->erm_black_list->create_time);
                $item->prove = $item->erm_black_list->prove;
                // $item->reason = $item->erm_black_list->reason;
                if ($item->record && $item->record->operator_id > 0) {
                    $item->reason = '手动加黑';
                    $item->remark = $item->erm_black_list->remark;
                }else{
                    $item->reason = $item->erm_black_list->remark;
                    $item->remark = '';
                }

                unset($item->erm_black_list);
            }
            $item->join_date = ceil((time() - $item->update_time) / 86400);
            $item->join_user = $item->admin->admin_name ?? '';
            /*认证状态*/
            $authentication_data = [];
            foreach ($item->erm_authentication_record as $item2) {
                $authentication_data[] = $authentication_type[$item2->type];
            }
            $item->authentication_data = $authentication_data;
            // 是否自动添加
            $item->auto = $item->record ? ($item->record->operator_id > 0 ? 0 : 1) : 1;
            unset($item->record);
            unset($item->admin);
            unset($item->operator_id);
            unset($item->update_time);
            unset($item->erm_authentication_record);
        }

        return $list;
    }

    /*添加人列表*/
    public function getOperatorList()
    {
        $admin_res = app("model_admin")->select('admin_id', 'admin_name')->get();
        return $admin_res;
    }

    /*大众名单详情*/
    public function getDetail($param, $type)
    {
        $ermPublicListModel = app("model_erm_public_list");
        $userDataModel = app('model_user_data');
        $whereArr['t1.type'] = $type;
        $whereArr['t1.id'] = $param['id'];
        $list = $ermPublicListModel
            ->from($ermPublicListModel->getTable() . ' as t1')
            ->selectRaw('t1.id,t2.nickname,t2.user_code,t1.user_id,t1.user_type,t1.register_time,t1.recharge_num,t1.recharge_money,t1.last_recharge_time,t1.gray_num,t1.black_num,t1.update_time,t1.operator_id,t1.user_id,t1.white_num')
            ->join($userDataModel->getTable() . ' as t2', 't1.user_id', '=', 't2.user_id')
            ->with("admin:admin_id,admin_name")
            ->with([
                'erm_authentication_record' => function ($query) {
                    $query->select('user_id', 'type', 'status')->where('status', 1);
                },
            ])
            ->where($whereArr)
            ->first();
        if (!$list) {
            throw new BasicException(100001);
        }

        $list['user_type'] = ErmEnum::USER_TYPE[$list['user_type']];
        $list['register_date'] = ceil((time() - $list['register_time']) / 86400);
        $list['register_time'] = date('Y-m-d H:i:s', $list['register_time']);
        $list['last_recharge_time'] = $list['last_recharge_time'] ? date('Y-m-d H:i:s', $list['last_recharge_time']) : '';

        $list['join_time'] = date('Y-m-d H:i:s', $list['update_time']);
        $list['join_date'] = ceil((time() - $list['update_time']) / 86400);
        $list['join_user'] = $list['admin']['admin_name'] ?? '';
        /*认证状态*/
        $recharge_auth = app("model_erm_authentication_record")->select('status', 'photo')->where(['user_id' => $list['user_id'], 'type' => 1, 'is_effect' => 0, 'detail_type' => ErmEnum::AUTO_REMOVE_GRAY_LIST])->orderBy('id', 'desc')->first();
        $list['recharge_auth'] = $recharge_auth ?? ['status' => 0];
        $withdraw_auth = app("model_erm_authentication_record")->select('status', 'photo')->where(['user_id' => $list['user_id'], 'type' => 3, 'is_effect' => 0, 'detail_type' => ErmEnum::AUTO_REMOVE_GRAY_LIST])->orderBy('id', 'desc')->first();
        $list['withdraw_auth'] = $withdraw_auth ?? ['status' => 0];
        $consumption_auth = app("model_erm_authentication_record")->select('status', 'photo')->where(['user_id' => $list['user_id'], 'type' => 2, 'is_effect' => 0, 'detail_type' => ErmEnum::AUTO_REMOVE_GRAY_LIST])->orderBy('id', 'desc')->first();
        $list['consumption_auth'] = $consumption_auth ?? ['status' => 0];
        $exchange_auth = app("model_erm_authentication_record")->select('status', 'photo')->where(['user_id' => $list['user_id'], 'type' => 4, 'is_effect' => 0, 'detail_type' => ErmEnum::AUTO_REMOVE_GRAY_LIST])->orderBy('id', 'desc')->first();
        $list['exchange_auth'] = $exchange_auth ?? ['status' => 0];
        unset($list['admin']);
        unset($list['operator_id']);
        unset($list['update_time']);
        unset($list['erm_authentication_record']);

        return $list;
    }

    /*充值记录*/
    public function getRechargeList($param, $page, $perPage, $type)
    {
        $where['user_id'] = $param['user_id'];
        $list = app('model_user_recharge')
            ->select('id', 'money', 'status', 'type', 'add_time', 'merchant_type', 'merchant_name')
            ->where($where)
            ->orderBy('add_time', 'desc')
            ->orderBy('pay_time', 'desc')
            ->paginate($perPage, ['*'], '', $page)->toArray();
        //查询所有收款商户信息
     //   $merchants = app('model_pay_merchant')->select('id', 'name')->pluck('name', 'id')->toArray();

        $this->userRechargeFieldConversion($list['data']);

//        foreach ($list['data'] as &$v) {
//            $v['merchant_name'] = $merchants[$v['merchant_type']] ?? '';
//        }

        return $list;
    }

    private function userRechargeFieldConversion(&$data)
    {
        foreach ($data as &$v) {
            $v['pay_type'] = CommonService::payType($v['type']);
            unset($v['type']);
            $v['add_time'] = date('Y-m-d H:i:s', $v['add_time']);

//            if ($v['pay_time'] > 0) {
//                $v['pay_time'] = date('Y-m-d H:i:s', $v['pay_time']);
//            } else {
//                $v['pay_time'] = '';
//            }
            if ($v['status'] == 1) {
                $v['pay_status'] = '未支付';
            } else {
                if ($v['status'] == 2) {
                    $v['pay_status'] = '已支付';
                } else {
                    $v['pay_status'] = '敬请期待';
                }
            }
            unset($v['status']);
        }
    }

    /*消费记录*/
    public function getConsumptionList($param, $page, $perPage, $type)
    {

        $changeType = ErmEnum::CHANGE_TYPE_CONSUMPTION['child_type'];

        $where[] = ['user_id', '=', $param['user_id']];
        $fields = ['id', 'user_id', 'change_money as user_money', 'change_type', 'created_at as change_time'];
        $list = app('model_account_money_log')
            ->select($fields)
            ->where($where)
            ->whereIn('change_type', $changeType)
            ->orderBy('change_time', 'desc')->paginate($perPage)->toArray();
        $data = $list['data'];

        //类型id与名称的映射
        $type_list = app('repo_account_log')->typeList();
        $type_list_arr = [];
        foreach ($type_list as $key => $val) {
            $type_list_arr[$val['change_type']] = $val['name'];
        }

        foreach ($data as &$v) {
            $v['change_type_name'] = $type_list_arr[$v['change_type']] ?? '';
        }
        $list['data'] = $data;

        return $list;
    }

    /*兑换记录*/
    public function getExchangeList($param, $page, $perPage, $type)
    {
        $changeType = array_merge(ErmEnum::CHANGE_TYPE_WITHDRAW['child_type'], ErmEnum::CHANGE_TYPE_EXCHANGE['child_type']);

        $where[] = ['t1.user_id', '=', $param['user_id']];
        $fields = ['t1.id', 't1.user_id', 't1.change_money as user_money', 't1.change_type', 't1.created_at as change_time', 't2.cardholder', 't2.bank_num', 't2.status', 't2.remark', 't2.money'];
        $accountLogModel = app('model_account_earnings_log');
        $withDrawModel = app('model_user_withdraw');
        $list = app('model_account_earnings_log')
            ->from($accountLogModel->getTable() . " as t1")
            ->leftJoin(DB::raw($withDrawModel->getTable() . " as t2"), "t1.source_id", "=", "t2.id")
            ->select($fields)
            ->where($where)
            ->whereIn('t1.change_type', $changeType)
            ->orderBy('change_time', 'desc')->paginate($perPage)->toArray();
        $data = $list['data'];

        //类型id与名称的映射
        $type_list = app('repo_account_log')->typeList();
        $type_list_arr = [];
        foreach ($type_list as $key => $val) {
            $type_list_arr[$val['change_type']] = $val['name'];
        }

        $status_name = [1 => '待审核', 2 => '通过', 3 => '拒绝'];
        foreach ($data as &$v) {
            $v['change_type_name'] = $type_list_arr[$v['change_type']] ?? '';
            $v['cardholder'] = $v['cardholder'] ? $this->str_replaces($v['cardholder'], 1, 1) : null;
            if ($v['status']) {
                $v['status'] = $status_name[$v['status']];
            }
            if ($v['money']) {
                $v['user_money'] = $v['money'];
            } else {
                $v['user_money'] = number_format(round($v['user_money'] / 100, 2), 2);
            }
            if ($v['bank_num']) {
                if (strpos($v['bank_num'], '@')) {
                    $string_len = strlen($v['bank_num']) - 3 - strlen(substr($v['bank_num'], strpos($v['bank_num'], '@')));
                    $v['bank_num'] = substr_replace($v['bank_num'], '****', 3, $string_len);;
                } else {
                    $string_len = strlen($v['bank_num']) - 3 - 4;
                    $v['bank_num'] = substr_replace($v['bank_num'], '****', 3, $string_len);;
                }
            }
        }
        $list['data'] = $data;

        return $list;
    }

    /**
     * @param $str
     * @param $start
     * @param $len
     * @param string $symbol
     * @return string
     */
    function str_replaces($str, $start, $len, $symbol = '*')
    {
        $end = $start + $len;
        // 截取头保留的字符
        $str1 = mb_substr($str, 0, $start);
        // 截取尾保留的字符
        $str2 = mb_substr($str, $end);

        //  生产要替换的字符
        $symbol_num = '';
        for ($i = 0; $i < $len; $i++) {
            $symbol_num .= $symbol;
        }
        return $str1 . $symbol_num . $str2;
    }

    /*名单变动*/
    public function joinList($param)
    {
        $public_list_res = app("model_erm_public_list")->where(['id' => $param['id'], 'type' => $param['old_type']])->first();
        if (!$public_list_res) {
            throw new BasicException(100001, '用户所属名单错误');
        }
        if ($public_list_res['type'] == $param['type']) {
            throw new BasicException(100001, '变动类型错误');
        }

        $param['remark'] = $param['remark'] ?? '';
        $param['admin_id'] = $param['admin_id'] ?? 0;
        $this->joinListWay($public_list_res['user_id'], $param['type'], $param['remark'], $param['admin_id'],$param);
    }

    /*名单变动*/
    public function joinListWay($user_id, $type, $remark = '', $admin_id = 0, $param = [])
    {
        $public_list_res = app("model_erm_public_list")->where(['user_id' => $user_id])->first();
        if (!$public_list_res) {
            throw new BasicException(100001, '用户所属名单错误');
        }
        if ($public_list_res['type'] == $type) {
            throw new BasicException(100001, '变动类型错误');
        }

        DB::beginTransaction();
        try {
            /*更新大众名单表*/
            $update_data = [
                'type' => $type,
                'operator_id' => $admin_id,
                'update_time' => time(),
            ];
            if ($type == ErmEnum::GRAY_TYPE) {
                $update_data['gray_num'] = DB::raw("gray_num+1");
            }
            if ($type == ErmEnum::BLACK_TYPE) {
                $update_data['black_num'] = DB::raw("black_num+1");
            }
            if ($type == ErmEnum::WHITE_TYPE) {//白名单数量加1
                $update_data['white_num'] = DB::raw("white_num+1");
            }

            $public_list_save = app("model_erm_public_list")->where(['id' => $public_list_res['id']])->update($update_data);
            if (!$public_list_save) {
                throw new BasicException(100002, '更新大众名单表失败');
            }

            /*名单变动记录*/
            $list_record_add = app("model_erm_list_record")->insert([
                'user_id' => $public_list_res['user_id'],
                'old_type' => $public_list_res['type'],
                'new_type' => $type,
                'operator_id' => $admin_id,
                'remark' => $remark ?? '',
                'create_time' => time(),
            ]);
            if (!$list_record_add) {
                throw new BasicException(100002, '名单变动记录失败');
            }

            /*移出名单*/
            if ($public_list_res['type'] != 1) {
                switch ($public_list_res['type']) {
                    case  ErmEnum::WHITE_TYPE:
                        $listModel = app("model_erm_white_list");
                        break;
                    case  ErmEnum::GRAY_TYPE:
                        $listModel = app("model_erm_gray_list");
                        break;
                    case  ErmEnum::BLACK_TYPE:
                        $listModel = app("model_erm_black_list");
                        break;
                }
                $list_del = $listModel->where(['user_id' => $public_list_res['user_id']])->delete();
                if (!$list_del) {
                    throw new BasicException(100002, '移出名单失败');
                }
            }

            /*移入名单*/
            if ($type != 1) {
                $insert_data = [
                    'user_id' => $public_list_res['user_id'],
                    'create_time' => time(),
                ];
                switch ($type) {
                    case  ErmEnum::WHITE_TYPE:
                        $listModel = app("model_erm_white_list");
                        $insert_data['expire_time'] = $param['expire_day'] ? time() + 86400 * $param['expire_day'] : 0;
                        $insert_data['remark'] = $remark ?? '';
                        break;
                    case  ErmEnum::GRAY_TYPE:
                        $listModel = app("model_erm_gray_list");
                        $insert_data['prove'] = $param['prove'] ?? '';
                        $insert_data['remark'] = $remark ?? '';
                        break;
                    case  ErmEnum::BLACK_TYPE:
                        $listModel = app("model_erm_black_list");
                        $insert_data['prove'] = $param['prove'] ?? '';
                        $insert_data['remark'] = $remark ?? '';
                        //拒绝用户提现申请
                        $this->blacklistbackGold($public_list_res['user_id']);
                        break;
                }
                $list_add = $listModel->insert($insert_data);
                if (!$list_add) {
                    throw new BasicException(100002, '移入名单失败');
                }
            }

            /*身份验证记录改为无效*/
            $erm_authentication_record = app("model_erm_authentication_record")->where(['user_id' => $public_list_res['user_id']])->update(['is_effect' => 1]);
            if ($erm_authentication_record === false) {
                throw new BasicException(100002, '身份验证记录改为无效失败');
            }
            /*连续支付次数清零*/
            $erm_pay_id_save = app("model_erm_pay_id")->where(['user_id' => $public_list_res['user_id'], ['continuity_num', '>', 0]])->update(['continuity_num' => 0]);
            if ($erm_pay_id_save === false) {
                throw new BasicException(100002, '连续支付次数清零失败');
            }
            /*删除缓存*/
            $redis_keys[] = sprintf(RedisKeyEnum::ERM_USER_ROLE, $public_list_res['user_id']);
            $redis_keys[] = sprintf(RedisKeyEnum::ERM_USER_AUTH_FAILED_NUM, $public_list_res['user_id'], 1);
            $redis_keys[] = sprintf(RedisKeyEnum::ERM_USER_AUTH_FAILED_NUM, $public_list_res['user_id'], 2);
            $redis_keys[] = sprintf(RedisKeyEnum::ERM_USER_AUTH_FAILED_NUM, $public_list_res['user_id'], 3);
            $redis_keys[] = sprintf(RedisKeyEnum::ERM_USER_AUTH_FAILED_NUM, $public_list_res['user_id'], 4);

            Redis::del($redis_keys);

            DB::commit();

        } catch (\Exception $e) {
            DB::rollBack();
            Log::error('名单变动失败:' . $e->getMessage() . json_encode(['user_id' => $user_id, 'type' => $type, 'remark' => $remark, 'admin_id' => $admin_id]));
            throw new BasicException(100002, $e->getMessage());
        }
    }

    /***
     * 提现退还
     * @param $user_id
     * @return void
     */
    public function blacklistbackGold($user_id)
    {
        //拒绝用户提现申请
        $withdraws = app('model_user_withdraw')->where([
            'user_id' => $user_id,
            'platform_status' => 1,
            'status'=>1,
        ])->get();

        foreach ($withdraws as $withdrawRecord){

            if (in_array($withdrawRecord->bank_type,[FinancialEnum::BANKCARD_WITHDRAW, FinancialEnum::COMPANY_WITHDRAW])) {
                app('model_user_withdraw')->where('id',$withdrawRecord->id)
                    ->update(['platform_status' => 3, 'fail_reason' => '后台加入黑名单']);
            } else {
                app('model_user_withdraw')->where('id',$withdrawRecord->id)
                    ->update(['platform_status' => 3, 'remark' => '后台加入黑名单']);
            }

            //回退用户收益
            app('repo_user')->serUserEarnings($user_id,
                $withdrawRecord->gold, 1);
            //更新资金日志
            app('model_account_earnings_log')
                ->where("source_id", $withdrawRecord->id)
                ->where("change_type", 23)
                ->update([
                    'change_desc' => '已退回',
                    'change_type' => 24,
                ]);
            $newBalanceInfo = app('repo_account')->getUserBalance($user_id);
            app('repo_account')->changeUserWithdrawableEarnings($user_id,
                $withdrawRecord->gold,
                1, 24, 1, $newBalanceInfo);
        }
    }


    /*同步用户到大众名单(上线后调用同步数据)*/
    public function syncToPublicList($sync_num = 1000)
    {
        /*获同步id*/
        $sync_public_key = RedisKeyEnum::ERM_SYNC_PUBLIC_ID;
        $sync_public_id = Redis::get($sync_public_key);
        $sync_public_id = $sync_public_id ?? 0;
        $sync_start = $sync_public_id;
        $sync_end = $sync_public_id + $sync_num;

        $last_user_recharge_res = app("model_user_recharge")->select('id')->where([['id', '>', $sync_start], ['id', '<=', $sync_end]])->orderBy('id', 'desc')->first();
        if (!$last_user_recharge_res) {
            return true;
        }
        $sync_end = $last_user_recharge_res['id'];
        $user_recharge_res = app("model_user_recharge")
            ->selectRaw('user_id,max(status) as status')
            ->with('user:user_id,register_time')
            ->where([['id', '>', $sync_start], ['id', '<=', $sync_end]])
            ->groupBy('user_id')
            ->get()->toArray();
        if (!$user_recharge_res) {
            return true;
        }

        /*加锁防止并发造成数据混乱，如果程序运行超时，锁定200秒*/
        $lock_second = 200;
        $lock_key = RedisKeyEnum::ERM_SYNC_PUBLIC_LOCK;
        $lock = Redis::setnx($lock_key, 1);
        if (!$lock) {
            throw new BasicException(100004);
        }
        Redis::expire($lock_key, $lock_second);

        DB::beginTransaction();
        try {
            $user_ids = array_column($user_recharge_res, 'user_id');
            $have_user_id = app("model_erm_public_list")->whereIn('user_id', $user_ids)->pluck('user_id')->toArray();
            $insert_data = [];
            foreach ($user_recharge_res as $k => $v) {
                if (!in_array($v['user_id'], $have_user_id) && $v['status'] == 2) {
                    $insert_data[] = [
                        'user_id' => $v['user_id'],
                        'register_time' => $v['user']['register_time'] ?? 0,
                        'create_time' => time(),
                    ];
                }
            }
            if ($insert_data) {
                $insert_res = app("model_erm_public_list")->insert($insert_data);
                if (!$insert_res) {
                    throw new BasicException(100003);
                }
            }

            /*更新同步id*/
            $redis_res = Redis::set($sync_public_key, $sync_end);
            if (!$redis_res) {
                throw new BasicException(100003);
            }
            /*解锁*/
            Redis::del($lock_key);

            DB::commit();

        } catch (\Exception $e) {
            DB::rollBack();
            throw new BasicException(100003, $e->getMessage());
        }

        return true;
    }


    /*同步用户类型*/
    public function syncUserType()
    {
        return ;
        /*用户类型*/
        $role_user_id = app("model_user")->where(['role' => 2])->pluck('user_id')->toArray();
        if ($role_user_id) {
            /*清空非官方管理*/
            $role_save = app("model_erm_public_list")->where(['user_type' => 2])->whereNotIn('user_id', $role_user_id)->update([
                'user_type' => 2
            ]);
            /*添加官方管理*/
            $role_save = app("model_erm_public_list")->whereIn('user_id', $role_user_id)->where([['user_type', '!=', 2]])->update([
                'user_type' => 2
            ]);
        }

        /*同步公会身份类型*/
        $erm_public_list_res = app('model_erm_public_list')->select('user_id', 'user_type')->get()->toArray();
        $sociaty_user_res = app('model_sc_sociaty_user')->select('user_id', 'type')->get()->keyBy('user_id')->toArray();
        $user_type_map = [
            1 => 3,
            2 => 4,
            3 => 5,
        ];
        if ($erm_public_list_res && $sociaty_user_res) {
            foreach ($erm_public_list_res as $k => $v) {
                if (isset($sociaty_user_res[$v['user_id']])) {
                    $sociaty_type = $user_type_map[$sociaty_user_res[$v['user_id']]['type']] ?? 0;
                    if ($sociaty_type != $v['user_type']) {
                        $role_save = app("model_erm_public_list")->where('user_id', $v['user_id'])->update([
                            'user_type' => $sociaty_type
                        ]);
                    }
                } else {
                    if (in_array($v['user_type'], [3, 4, 5])) {
                        $role_save = app("model_erm_public_list")->where('user_id', $v['user_id'])->update([
                            'user_type' => 1
                        ]);
                    }
                }
            }
        }
    }


    /*用户收益、消费统计*/
    public function statisticAmount($sync_num = 600)
    {
        /*累计收益统计account_money_log表*/
        $this->statisticEarningsOne($sync_num);
        /*累计收益统计account_earnings_log表*/
        $this->statisticEarningsTwo($sync_num);
        /*累计消费统计*/
        $this->statisticConsume($sync_num);
    }

    /**
     * Notes:累计消费统计
     * User: shengxuyao
     * DateTime: 2022/2/26 20:38
     */
    public function statisticConsume($sync_num = 1000)
    {
        /*获同步id*/
        $sync_public_key = RedisKeyEnum::ERM_STATISTIC_CONSUME_ID;
        $sync_public_id = Redis::get($sync_public_key);
        $sync_public_id = $sync_public_id ?? 0;
        $sync_start = $sync_public_id;
        $sync_end = $sync_public_id + $sync_num;

        $last_user_recharge_res = app("model_account_money_log")->select('id')->where([['id', '>', $sync_start], ['id', '<=', $sync_end]])->orderBy('id', 'desc')->first();
        if (!$last_user_recharge_res) {
            /*处理有主键id被删除的情况*/
            $have_recharge_res = app("model_account_money_log")->select('id')->where([['id', '>', $sync_end]])->orderBy('id', 'asc')->first();
            if ($have_recharge_res && $have_recharge_res['id'] > $sync_end) {
                $redis_res = Redis::set($sync_public_key, $have_recharge_res['id']);
            }

            return true;
        }

        /*加锁防止并发造成数据混乱，如果程序运行超时，锁定200秒*/
        $lock_second = 200;
        $lock_key = RedisKeyEnum::ERM_STATISTIC_CONSUME_LOCK;
        $lock = Redis::setnx($lock_key, 1);
        if (!$lock) {
            throw new BasicException(100004);
        }
        Redis::expire($lock_key, $lock_second);

        $sync_end = $last_user_recharge_res['id'];
        $consume_res = app("model_account_money_log")
            ->selectRaw('user_id,count(user_id) as consume_num,sum(change_money) as consume_money,max(created_at) as last_consume_time')
            ->where([['id', '>', $sync_start], ['id', '<=', $sync_end]])
            ->whereIn('change_type', ErmEnum::CHANGE_TYPE_CONSUMPTION['child_type'])
            ->groupBy('user_id')
            ->get()->toArray();
        if (!$consume_res) {
            /*更新同步id*/
            $redis_res = Redis::set($sync_public_key, $sync_end);
            if (!$redis_res) {
                throw new BasicException(100006);
            }
            /*解锁*/
            Redis::del($lock_key);

            return true;
        }
        $user_ids = [];
        DB::beginTransaction();
        try {
            /*累计消费*/
            if ($consume_res) {
                $user_ids = array_column($consume_res, 'user_id');
                $have_user_id = app("model_erm_statistic_amount")->whereIn('user_id', $user_ids)->pluck('user_id')->toArray();
                $insert_data = [];
                foreach ($consume_res as $k => $v) {
                    if (!in_array($v['user_id'], $have_user_id)) {
                        $insert_data[] = [
                            'user_id'           => $v['user_id'],
                            'consume_num'       => $v['consume_num'],
                            'consume_money'     => $v['consume_money'],
                            'last_consume_time' => strtotime($v['last_consume_time']),
                            'create_time'       => time(),
                        ];
                    } else {
                        app("model_erm_statistic_amount")->where(['user_id' => $v['user_id']])->update([
                            'consume_num'       => DB::raw("consume_num+" . $v['consume_num']),
                            'consume_money'     => DB::raw("consume_money+" . $v['consume_money']),
                            'last_consume_time' => strtotime($v['last_consume_time']),
                            'update_time'       => time(),
                        ]);
                    }
                }
                if ($insert_data) {
                    $insert_res = app("model_erm_statistic_amount")->insert($insert_data);
                    if (!$insert_res) {
                        throw new BasicException(100006);
                    }
                }
            }

            /*更新同步id*/
            $redis_res = Redis::set($sync_public_key, $sync_end);
            if (!$redis_res) {
                throw new BasicException(100006);
            }
            /*解锁*/
            Redis::del($lock_key);

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            throw new BasicException(100006, $e->getMessage());
        }

        /*用户余额和收益发生变动时，同步到大众名单*/
        if (!empty($user_ids)) {
            $this->statisticSyncToPublicList($user_ids);
        }
        return true;
    }

    /*用户余额和收益发生变动时，同步到大众名单*/
    public function statisticSyncToPublicList($userIds)
    {
        if (empty($userIds)) {
            return false;
        }

        $ermPublicListRes = app("model_erm_public_list")
            ->select('user_id')
            ->whereIn('user_id', $userIds)
            ->get()->toArray();
        $haveUserIds = array_column($ermPublicListRes, 'user_id');
        $syncUserIds = array_diff($userIds, $haveUserIds);
        if (empty($syncUserIds)) {
            return false;
        }

        foreach ($syncUserIds as $k => $v) {
            // 资金余额变动同步到大众名单
            app('repo_erm_public_list')->changeSyncToPublicList($v);
        }
    }

    /**
     * Notes:累计收益统计account_money_log表
     * User: shengxuyao
     * DateTime: 2022/2/26 20:38
     */
    public function statisticEarningsOne($sync_num = 1000)
    {
        /*获同步id*/
        $sync_public_key = RedisKeyEnum::ERM_STATISTIC_EARNINGS_ONE_ID;
        $sync_public_id = Redis::get($sync_public_key);
        $sync_public_id = $sync_public_id ?? 0;
        $sync_start = $sync_public_id;
        $sync_end = $sync_public_id + $sync_num;

        $last_user_recharge_res = app("model_account_money_log")->select('id')->where([['id', '>', $sync_start], ['id', '<=', $sync_end]])->orderBy('id', 'desc')->first();
        if (!$last_user_recharge_res) {
            /*处理有主键id被删除的情况*/
            $have_recharge_res = app("model_account_money_log")->select('id')->where([['id', '>', $sync_end]])->orderBy('id', 'asc')->first();
            if ($have_recharge_res && $have_recharge_res['id'] > $sync_end) {
                $redis_res = Redis::set($sync_public_key, $have_recharge_res['id']);
            }

            return true;
        }

        /*加锁防止并发造成数据混乱，如果程序运行超时，锁定200秒*/
        $lock_second = 200;
        $lock_key = RedisKeyEnum::ERM_STATISTIC_EARNINGS_ONE_LOCK;
        $lock = Redis::setnx($lock_key, 1);
        if (!$lock) {
            throw new BasicException(100004);
        }
        Redis::expire($lock_key, $lock_second);

        $sync_end = $last_user_recharge_res['id'];
        $earnings_res = app("model_account_money_log")
            ->selectRaw('user_id,count(user_id) as earnings_num,sum(change_money) as earnings_money,max(created_at) as last_earnings_time')
            ->where([['id', '>', $sync_start], ['id', '<=', $sync_end]])
            ->whereIn('change_type', ErmEnum::EARNINGS_TYPE_MONEY_TB)
            ->groupBy('user_id')
            ->get()->toArray();
        if (!$earnings_res) {
            /*更新同步id*/
            $redis_res = Redis::set($sync_public_key, $sync_end);
            if (!$redis_res) {
                throw new BasicException(100006);
            }
            /*解锁*/
            Redis::del($lock_key);

            return true;
        }
        $user_ids = [];

        DB::beginTransaction();
        try {
            /*累计收益*/
            if ($earnings_res) {
                $user_ids = array_column($earnings_res, 'user_id');
                $have_user_id = app("model_erm_statistic_amount")->whereIn('user_id', $user_ids)->pluck('user_id')->toArray();
                $insert_data = [];
                foreach ($earnings_res as $k => $v) {
                    if (!in_array($v['user_id'], $have_user_id)) {
                        $insert_data[] = [
                            'user_id'            => $v['user_id'],
                            'earnings_num'       => $v['earnings_num'],
                            'earnings_money'     => $v['earnings_money'],
                            'last_earnings_time' => strtotime($v['last_earnings_time']),
                            'create_time'        => time(),
                        ];
                    } else {
                        app("model_erm_statistic_amount")->where(['user_id' => $v['user_id']])->update([
                            'earnings_num'       => DB::raw("earnings_num+" . $v['earnings_num']),
                            'earnings_money'     => DB::raw("earnings_money+" . $v['earnings_money']),
                            'last_earnings_time' => strtotime($v['last_earnings_time']),
                            'update_time'        => time(),
                        ]);
                    }
                }
                if ($insert_data) {
                    $insert_res = app("model_erm_statistic_amount")->insert($insert_data);
                    if (!$insert_res) {
                        throw new BasicException(100006);
                    }
                }
            }

            /*更新同步id*/
            $redis_res = Redis::set($sync_public_key, $sync_end);
            if (!$redis_res) {
                throw new BasicException(100006);
            }
            /*解锁*/
            Redis::del($lock_key);

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            throw new BasicException(100006, $e->getMessage());
        }

        /*用户余额和收益发生变动时，同步到大众名单*/
        if (!empty($user_ids)) {
            $this->statisticSyncToPublicList($user_ids);
        }
        return true;
    }

    /**
     * Notes:累计收益统计account_earnings_log表
     * User: shengxuyao
     * DateTime: 2022/2/26 20:38
     */
    public function statisticEarningsTwo($sync_num = 1000)
    {
        /*获同步id*/
        $sync_public_key = RedisKeyEnum::ERM_STATISTIC_EARNINGS_TWO_ID;
        $sync_public_id = Redis::get($sync_public_key);
        $sync_public_id = $sync_public_id ?? 0;
        $sync_start = $sync_public_id;
        $sync_end = $sync_public_id + $sync_num;

        $last_user_recharge_res = app("model_account_earnings_log")->select('id')->where([['id', '>', $sync_start], ['id', '<=', $sync_end]])->orderBy('id', 'desc')->first();
        if (!$last_user_recharge_res) {
            /*处理有主键id被删除的情况*/
            $have_recharge_res = app("model_account_earnings_log")->select('id')->where([['id', '>', $sync_end]])->orderBy('id', 'asc')->first();
            if ($have_recharge_res && $have_recharge_res['id'] > $sync_end) {
                $redis_res = Redis::set($sync_public_key, $have_recharge_res['id']);
            }

            return true;
        }

        /*加锁防止并发造成数据混乱，如果程序运行超时，锁定200秒*/
        $lock_second = 200;
        $lock_key = RedisKeyEnum::ERM_STATISTIC_EARNINGS_TWO_LOCK;
        $lock = Redis::setnx($lock_key, 1);
        if (!$lock) {
            throw new BasicException(100004);
        }
        Redis::expire($lock_key, $lock_second);

        $sync_end = $last_user_recharge_res['id'];
        $earnings_res = app("model_account_earnings_log")
            ->selectRaw('user_id,count(user_id) as earnings_num,sum(change_money) as earnings_money,max(created_at) as last_earnings_time')
            ->where([['id', '>', $sync_start], ['id', '<=', $sync_end]])
            ->whereIn('change_type', ErmEnum::EARNINGS_TYPE_EARNINGS_TB)
            ->groupBy('user_id')
            ->get()->toArray();
        if (!$earnings_res) {
            /*更新同步id*/
            $redis_res = Redis::set($sync_public_key, $sync_end);
            if (!$redis_res) {
                throw new BasicException(100006);
            }
            /*解锁*/
            Redis::del($lock_key);

            return true;
        }
        $user_ids = [];
        DB::beginTransaction();
        try {
            /*累计收益*/
            if ($earnings_res) {
                $user_ids = array_column($earnings_res, 'user_id');
                $have_user_id = app("model_erm_statistic_amount")->whereIn('user_id', $user_ids)->pluck('user_id')->toArray();
                $insert_data = [];
                foreach ($earnings_res as $k => $v) {
                    if (!in_array($v['user_id'], $have_user_id)) {
                        $insert_data[] = [
                            'user_id'            => $v['user_id'],
                            'earnings_num'       => $v['earnings_num'],
                            'earnings_money'     => $v['earnings_money'],
                            'last_earnings_time' => strtotime($v['last_earnings_time']),
                            'create_time'        => time(),
                        ];
                    } else {
                        app("model_erm_statistic_amount")->where(['user_id' => $v['user_id']])->update([
                            'earnings_num'       => DB::raw("earnings_num+" . $v['earnings_num']),
                            'earnings_money'     => DB::raw("earnings_money+" . $v['earnings_money']),
                            'last_earnings_time' => strtotime($v['last_earnings_time']),
                            'update_time'        => time(),
                        ]);
                    }
                }
                if ($insert_data) {
                    $insert_res = app("model_erm_statistic_amount")->insert($insert_data);
                    if (!$insert_res) {
                        throw new BasicException(100006);
                    }
                }
            }

            /*更新同步id*/
            $redis_res = Redis::set($sync_public_key, $sync_end);
            if (!$redis_res) {
                throw new BasicException(100006);
            }
            /*解锁*/
            Redis::del($lock_key);

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            throw new BasicException(100006, $e->getMessage());
        }
        /*用户余额和收益发生变动时，同步到大众名单*/
        if (!empty($user_ids)) {
            $this->statisticSyncToPublicList($user_ids);
        }
        return true;
    }


    /*同步用户历史充值金额(上线后调用同步数据)*/
    public function syncRechargeMoney($page, $perPage = 1000)
    {
        $erm_public_list_res = app("model_erm_public_list")->select('user_id')->orderBy('id', 'asc')->paginate($perPage, ['*'], '', $page)->toArray();
        $user_ids = array_column($erm_public_list_res['data'], 'user_id');
        if (!$user_ids) {
            throw new BasicException(10001, 'user_ids错误');
        }
        $user_recharge_res = app("model_user_recharge")
            ->selectRaw('user_id,count(user_id) as recharge_num,sum(money) as recharge_money,max(add_time) as last_recharge_time,max(pay_time) as last_pay_time')
            ->where(['status' => 2])
            ->whereIn('user_id', $user_ids)
            ->groupBy('user_id')
            ->get()->toArray();
        $user_recharge_res = array_column($user_recharge_res, null, 'user_id');

        $update_data = [];
        foreach ($user_ids as $k => $v) {
            if (isset($user_recharge_res[$v])) {
                $last_recharge_time = $user_recharge_res[$v]['last_recharge_time'] ? $user_recharge_res[$v]['last_recharge_time'] : $user_recharge_res[$v]['last_pay_time'];
                $update_data[] = [
                    'user_id' => $v,
                    'recharge_num' => $user_recharge_res[$v]['recharge_num'],
                    'recharge_money' => $user_recharge_res[$v]['recharge_money'],
                    'last_recharge_time' => $last_recharge_time,
                ];
            }
        }

        if ($update_data) {
            $sql = $this->updateBatch('ln_erm_public_list', $update_data);
            $update_res = DB::connection('mysql')->update($sql);
            if ($update_res === false) throw new BasicException(10001, '更新失败');
        }

        return true;
    }


    public function updateBatch($tableName = "", $multipleData = array())
    {

        if ($tableName && !empty($multipleData)) {

            // column or fields to update
            $updateColumn = array_keys($multipleData[0]);
            $referenceColumn = $updateColumn[0]; //e.g id
            unset($updateColumn[0]);
            $whereIn = "";

            $q = "UPDATE " . $tableName . " SET ";
            foreach ($updateColumn as $uColumn) {
                $q .= $uColumn . " = CASE ";

                foreach ($multipleData as $data) {
                    $q .= "WHEN " . $referenceColumn . " = " . $data[$referenceColumn] . " THEN '" . $data[$uColumn] . "' ";
                }
                $q .= "ELSE " . $uColumn . " END, ";
            }
            foreach ($multipleData as $data) {
                $whereIn .= "'" . $data[$referenceColumn] . "', ";
            }
            $q = rtrim($q, ", ") . " WHERE " . $referenceColumn . " IN (" . rtrim($whereIn, ', ') . ")";

            // Update
            return $q;

        } else {
            return false;
        }

    }

    /**
     * 获取用户名单记录明细
     *
     * @param int $userId
     * @return mixed
     */
    public function recordList($userId)
    {
        $res = app('model_erm_list_record')
            ->select('old_type', 'new_type', 'create_time', 'remark','user_id', 'operator_id')
            ->with('erm_public_list:user_id,create_time')
            ->where(['user_id' => $userId])
            ->orderBy('id', 'desc')
            ->get();

        foreach ($res as $k=>$v) {
            $v->create_time = date('Y-m-d H:i:s', $v->create_time);
            $v->old = ErmEnum::TYPE_MAP[$v->old_type];
            $v->new = ErmEnum::TYPE_MAP[$v->new_type];
            // if($v->remark){
            //     $remark = strpos(':',$v->remark) !== false ? explode(':',$v->remark) : explode('：',$v->remark);
            //     $remark = count($remark) > 1 ? $remark[1] : $remark[0];
            // }
            if(isset($res[$k+1])){
                $v->join_time =  date('Y-m-d H:i:s', $res[$k+1]->create_time);
            }else{
                $v->join_time =  date('Y-m-d H:i:s', $v->erm_public_list->create_time);
            }
            if ($v->operator_id > 0){
                if ($v->new_type == 1){
                    if ($v->old_type == 2){
                        $v->remark = '手动去白';
                    } elseif ($v->old_type == 3){
                        $v->remark = '手动去灰';
                    } elseif ($v->old_type == 4){
                        $v->remark = '手动去黑';
                    }
                } else {
                    if ($v->new_type == 2){
                        $v->remark = '手动加白';
                    } elseif ($v->new_type == 3){
                        $v->remark = '手动加灰';
                    } elseif ($v->new_type == 4){
                        $v->remark = '手动加黑';
                    }
                }
            }
            unset($v->erm_public_list);
        }
        return $res;
    }

    /**
     * 加灰原因
     */
    public function grayReasonList()
    {
        $list = app('model_erm_list_record')
            ->where('new_type', ErmEnum::GRAY_TYPE)
            ->where('operator_id', 0)
            ->where('remark', '!=', '')
            ->groupBy('remark')
            ->pluck('remark')
            ->toArray();
        $reasonList = ['手动加灰'];
        foreach ($list as $v) {
            if (strpos($v, ':') !== false) {
                $tmp = explode(':', $v)[1];
            } elseif (strpos($v, '：') !== false) {
                $tmp = explode('：', $v)[1];
            } else {
                $tmp = $v;
            }
            $reasonList[$tmp] = $tmp;
        }

        return array_values($reasonList);
    }

    /**
     * 加黑原因
     */
    public function blackReasonList(){
        $list = app('model_erm_list_record')
            ->where('new_type', ErmEnum::BLACK_TYPE)
            ->where('operator_id', 0)
            ->where('remark', '!=', '')
            ->groupBy('remark')
            ->pluck('remark')
            ->toArray();
        $reasonList = ['手动加黑'];
        foreach ($list as $v) {
            if (strpos($v, ':') !== false) {
                $tmp = explode(':', $v)[1];
            } elseif (strpos($v, '：') !== false) {
                $tmp = explode('：', $v)[1];
            } else {
                $tmp = $v;
            }
            $reasonList[$tmp] = $tmp;
        }

        return array_values($reasonList);
    }

    /* 用户账户资金变动同步到大众名单  */
    public function changeSyncToPublicList($user_id)
    {
        $isHave = app("model_erm_public_list")->select('id')->where('user_id', $user_id)->first();
        if (!$isHave) {
            $user_res = app("model_user")->select('register_time')->where('user_id', $user_id)->first();
            app("model_erm_public_list")->insert([
                'user_id'            => $user_id,
                'register_time'      => $user_res['register_time'] ?? 0,
                'recharge_num'       => 0,
                'recharge_money'     => 0,
                'last_recharge_time' => 0,
                'create_time'        => time(),
                'update_time'        => time(),
            ]);
        }
    }
}
